<template>
  <div>
    <Card title="安全设置" class="w-1/2 !m-10px min-w-700px">
      <BasicForm @register="registerSetting" />
      <div class="float-right">
        <Button @click="resetSetting" :disabled="!hasSettingEdit">撤销</Button>
        <Button type="primary" class="ml-12px" @click="saveSetting" :disabled="!hasSettingEdit"
          >保存</Button
        >
      </div>
    </Card>
    <Card title="JWT安全设置" class="w-1/2 !m-10px min-w-700px">
      <BasicForm @register="registerJWT">
        <template #tokenSigningKey="{ model, field }">
          <Input v-model:value="model[field]" :allowClear="true" @change="hasJWtEdit = true">
            <template #suffix>
              <Button size="small" type="primary" @click="createKey(model, field)">生成密钥</Button>
            </template>
          </Input>
        </template>
      </BasicForm>
      <div class="float-right">
        <Button @click="resetJWT" :disabled="!hasJWtEdit">撤销</Button>
        <Button type="primary" class="ml-12px" @click="saveJWT" :disabled="!hasJWtEdit"
          >保存</Button
        >
      </div>
    </Card>
  </div>
</template>

<script lang="ts" setup>
  import { Card, Input, Button } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { securitySettings, JWTSettings, hasSettingEdit, hasJWtEdit } from './basic.data';
  import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
  import {
    getSecuritySetting,
    postSecuritySetting,
    getJWTSetting,
    postJWTSetting,
  } from '/@/api/thingsborad/security/basicSetting/basicSetting';
  import { onMounted, ref, watch } from 'vue';
  import { useSystemStatusStoreWithOut } from '/@/store/modules/thingsboard/systemStatus';
  //安全设置修改前的数据
  let securitySetting = ref<Recordable>({});
  let JWTSetting = ref<Recordable>({});
  onMounted(async () => {
    await getSecurity();
    await getJWT();
    //按钮复位
    hasJWtEdit.value = false;
    hasSettingEdit.value = false;
  });

  //获取安全设置
  async function getSecurity() {
    try {
      securitySetting.value = await getSecuritySetting();
      await setSettingFieldValue(securitySetting.value);
    } catch (e) {}
  }
  //获取JWT设置
  async function getJWT() {
    try {
      JWTSetting.value = await getJWTSetting();
      await setJWTFieldsValue(JWTSetting.value);
    } catch (e) {}
  }
  // 安全设置
  const [
    registerSetting,
    {
      setFieldsValue: setSettingFieldValue,
      validate: validateSetting,
      getFieldsValue: getSettingFieldValue,
    },
  ] = useForm({
    layout: 'vertical',
    schemas: securitySettings,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  // JWT安全设置
  const [
    registerJWT,
    { setFieldsValue: setJWTFieldsValue, validate: JWTvalidate, setProps: setJWTProps },
  ] = useForm({
    layout: 'vertical',
    schemas: JWTSettings,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  const useStore = useSystemStatusStoreWithOut();
  watch(
    [() => hasJWtEdit.value, () => hasSettingEdit.value],
    ([jwtVal, settingVal]) => {
      useStore.setIsDataChanged(jwtVal || settingVal);
    },
    {
      immediate: false,
    },
  );
  const alphanumericCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const alphanumericCharactersLength = alphanumericCharacters.length;
  //密钥生成
  function randomAlphanumeric(length: number): string {
    let result = '';
    for (let i = 0; i < length; i++) {
      result += alphanumericCharacters.charAt(
        Math.floor(Math.random() * alphanumericCharactersLength),
      );
    }
    return result;
  }
  async function createKey(model: any, field: string) {
    model[field] = btoa(randomAlphanumeric(64));
    await JWTvalidate();
    setJWTProps({
      submitButtonOptions: {
        disabled: false,
      },
      resetButtonOptions: {
        disabled: false,
      },
    });
    hasJWtEdit.value = true;
  }
  //安全设置撤销
  async function resetSetting() {
    await getSecurity();
    hasSettingEdit.value = false;
  }
  //安全设置保存
  async function saveSetting() {
    await validateSetting();
    let res: Recordable = getSettingFieldValue();
    try {
      await postSecuritySetting(res);
      hasSettingEdit.value = false;
    } catch (e) {}
  }
  //JWT设置撤销
  async function resetJWT() {
    await getJWT();
    hasJWtEdit.value = false;
  }
  //JWT设置保存
  async function saveJWT() {
    let res: Recordable = await JWTvalidate();
    try {
      await postJWTSetting(res);
      hasJWtEdit.value = false;
    } catch (e) {}
  }
</script>
